<template>
  <page-title/>
  <div>
    <q-table
        :rows="tags"
        :columns="tableColumns"
        row-key="id"
        :loading="loading"
        v-model:pagination="pagination"
        @request="onRequest"
    >
      <template v-slot:top>
        <q-btn color="primary" label="新增" @click="saveOrEditTag()"/>
        <q-space/>
        <q-toggle
            color="primary"
            keep-color
            v-model="autoRefresh"
            @click="!autoRefresh"
            label="自动刷新(5s)"/>
      </template>

      <template v-slot:header="props">
        <q-tr :props="props">
          <q-th
              v-for="col in props.cols"
              :key="col.name"
              :props="props"
              class="text-primary"
          >
            {{ col.label }}
          </q-th>
        </q-tr>
      </template>

      <template v-slot:body-cell-active="props">
        <q-td :props="props">
          <div>
            <!-- v-model 要用响应式数据，props.value 是只读属性，不能用于响应式 -->
            <q-toggle
                color="primary"
                keep-color
                @click="switchById(props.row.id)"
                v-model="props.row.active"/>
          </div>
        </q-td>
      </template>

      <template v-slot:body-cell-tagName="props">
        <q-td :props="props">
          <div>
            {{props.row.tagName}}
            <q-badge color="primary">
              {{formatPrefix(props.row.prefixId)}}
            </q-badge>
          </div>
        </q-td>
      </template>

      <template v-slot:body-cell-action="props">
        <q-td :props="props">
          <div>
            <q-btn-group rounded>
              <q-btn rounded size="md" color="primary" label="编辑" @click="saveOrEditTag(props.row.id)"/>
              <q-btn rounded size="md" color="red-4" label="删除" @click="remove(props.row.id)"/>
            </q-btn-group>
          </div>
        </q-td>
      </template>
    </q-table>
  </div>
</template>

<script lang="ts">
import {QBadge, QBtn, QBtnGroup, QSpace, QTable, QTd, QTh, QToggle, QTr} from "quasar";
import {defineComponent, onMounted, ref} from "vue";
import {useTag} from "../../hooks/useTag";
import {showDialog} from "../../utils/dialog";
import {TableFetchDataProps} from "../../types/TableFetchDataProps";
import {defaultPaginationConfig, PaginationConfig} from "../../types/paginationConfig";
import TagEdit from "./components/TagEdit.vue";
import PageTitle from '../../components/common/PageTitle.vue'
import {Prefix} from "../../types/prefix";

export default defineComponent({
  name: "TagList",
  components: {
    QTable,
    QTr,
    QTh,
    QTd,
    QBadge,
    QToggle,
    QBtnGroup,
    QBtn,
    QSpace,
    PageTitle,
  },
  setup: function () {
    const {tags, tableColumns, loading, listPaging, remove, switchById, getById, add, edit, init, prefixOptions} = useTag()

    // 分页配置
    const pagination = ref<PaginationConfig>(defaultPaginationConfig)

    // 表格自动刷新
    const autoRefresh = ref<boolean>(false)

    const prefixes = ref<Prefix[]>([])

    // 加载分页数据
    async function loadData(pageNo: number, pageSize: number): Promise<void> {
      pagination.value = await listPaging(pageNo, pageSize)
      prefixes.value = await prefixOptions()
    }

    function formatPrefix(prefixId: number) {
      const target = prefixes.value?.find(prefix => prefix.id === prefixId)
      return target ? target.name : '---'
    }

    onMounted(() => {
      loadData(pagination.value.page, pagination.value.rowsPerPage)
    })

    // 由于 onMounted 的时候使用 prefix 的 hooks 获取了前缀数据，并且添加了一个 id=-1 的选项
    // 所以在组件卸载的时候要把这个添加的选项删掉，否则切换到前缀列表页会短暂出现一个新增 item
    // onBeforeUnmount(() => {
    //   prefixes.value.splice(0, 1)
    // })

    // 表格分页数据请求
    function onRequest(fetchProps: TableFetchDataProps): void {
      const {
        page = defaultPaginationConfig.page,
        rowsPerPage = defaultPaginationConfig.rowsPerPage
      } = fetchProps.pagination
      loadData(page, rowsPerPage)
    }

    // 编辑或新增标签
    async function saveOrEditTag(tagId: number = -1): Promise<void> {
      showDialog({
        component: TagEdit,
        componentProps: {
          title: tagId === -1 ? '新增标签' : '编辑标签',
          id: tagId,
          init: init(),
          getById,
          add,
          edit,
          options: prefixes.value,
        },
      }).onDismiss(() => {
        loadData(pagination.value.page, pagination.value.rowsPerPage)
      })
    }

    // const switchModel = (tagId: number) => {
    //   const target = tags.value.find(tag => tag.id === tagId)
    //   if (target) {
    //
    //   }
    // }

    return {
      tags,
      loading,
      pagination,
      tableColumns,
      saveOrEditTag,
      remove,
      switchById,
      onRequest,
      autoRefresh,
      formatPrefix,
    }
  }
})
</script>

<style scoped>

</style>